<?php

namespace App\Services;

use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Ocr\V20181119\OcrClient;
use TencentCloud\Ocr\V20181119\Models\GeneralBasicOCRRequest;

class OcrService
{
    protected $client;

    public function __construct()
    {
        try {
            // 实例化一个认证对象，入参需要传入腾讯云账户密钥对secretId，secretKey
            $cred = new Credential(
                config('services.tencent_api.key'),
                config('services.tencent_api.secret')
            );

            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("ocr.tencentcloudapi.com");

            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);

            // 实例化要请求产品的client对象,clientProfile是可选的
            $this->client = new OcrClient($cred, "ap-guangzhou", $clientProfile);
        } catch (TencentCloudSDKException $e) {
            throw $e;
        }
    }

    public function recognizeImage($imagePath)
    {
        try {
            // 实例化一个请求对象,每个接口都会对应一个request对象
            $req = new GeneralBasicOCRRequest();

            // 读取图片内容并base64编码
            $imageContent = file_get_contents(storage_path('app/public/' . $imagePath));
            $base64Image = base64_encode($imageContent);
            
            $params = array(
                "ImageBase64" => $base64Image
            );
            $req->fromJsonString(json_encode($params));

            // 返回的resp是一个GeneralBasicOCRResponse的实例，与请求对象对应
            $resp = $this->client->GeneralBasicOCR($req);
            
            // 提取文本内容
            $textArray = [];
            foreach ($resp->TextDetections as $text) {
                $textArray[] = $text->DetectedText;
            }
            
            return implode("\n", $textArray);
        } catch (TencentCloudSDKException $e) {
            \Log::error('OCR识别失败：' . $e->getMessage());
            throw $e;
        }
    }
} 